package com.qf.mybatisplus.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author code
 */
public class FileUtils {


    private final static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 文件上传
     *
     * @param file     文件
     * @param filePath 存储路径
     * @param fileName 文件名称
     * @throws Exception
     */

    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    /**
     * @param MultiFile 二进制文件
     * @param path      文件存储路径
     * @return boolean
     */
    public static String MultipartFileUpload(MultipartFile MultiFile, String path) {
        if (MultiFile.getSize() < 1) {
            //文件为空
            return null;
        }
        //获取文件名
        String orgFileName = MultiFile.getOriginalFilename();
        //获取String类型的时间字符串
        SimpleDateFormat format0 = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateTime = format0.format(new Date());
        StringBuilder fileName = new StringBuilder(path);
        fileName.append(dateTime).append(orgFileName);
        //保存文件
        File file = new File(fileName.toString());

        if (!file.exists()) {
            try {
                createDirectoryAndFile(file);
                MultiFile.transferTo(file);
            } catch (IOException e) {
                logger.info("文件转换异常{}", e);
                e.printStackTrace();
                return null;
            }
        }
        return fileName.toString();
    }

    /**
     * 创建文件或者文件夹
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static boolean createDirectoryAndFile(File file) throws IOException {
        String path = file.getPath();
        String name = file.getName();
        if (name.contains(".")) {
            String directoryStr = path.substring(0, path.length() - name.length());
            File directory = new File(directoryStr);
            if (!directory.exists()) {
                if (directory.mkdirs() && createFile(file)) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 创建文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static boolean createFile(File file) throws IOException {
        RandomAccessFile accessFile = null;
        try {
            if (!file.exists()) {
                accessFile = new RandomAccessFile(file, "rw");
                return true;
            } else {
                if (file.isDirectory()) {
                    throw new IOException(file.getPath() + " 已存在, 但是它是文件夹");
                } else {
                    return true;
                }
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (accessFile != null) {
                accessFile.close();
            }
        }
    }

    /**
     * 递归删除文件或者目录
     *
     * @param file_path
     */
    public static void deleteEveryThing(String file_path) {
        try {
            File file = new File(file_path);
            if (!file.exists()) {
                return;
            }
            if (file.isFile()) {
                boolean delete = file.delete();
                logger.info("文件删除：{}", delete);
            } else {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    String root = files[i].getAbsolutePath();//得到子文件或文件夹的绝对路径
                    deleteEveryThing(root);
                }
                boolean delete = file.delete();
                logger.info("文件删除：{}", delete);
            }
        } catch (Exception e) {
            System.out.println("删除文件失败");
        }
    }


    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
